package com.idlecode.config.query;

import cn.hutool.core.util.StrUtil;
import com.idlecode.config.DbType;

/**
 * ClickHouse 表数据查询
 */
public class ClickHouseQuery implements AbstractQuery {

    @Override
    public DbType dbType() {
        return DbType.Clickhouse;
    }

    @Override
    public String dbNamesSql() {
        return "SELECT name as OWNER FROM system.databases order by name";
    }

    @Override
    public String tableSql(String dataBaseName, String tableName) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT name, comment  FROM system.tables WHERE database = '").append(dataBaseName).append("' ");

        // 表名查询
        if (StrUtil.isNotBlank(tableName)) {
            sql.append("and name = '").append(tableName).append("' ");
        }
        return sql.toString();
    }

    @Override
    public String dbName() {
        return "OWNER";
    }

    @Override
    public String tableName() {
        return "name";
    }

    @Override
    public String tableComment() {
        return "comment";
    }

    @Override
    public String tableUpdateTime() {
        return null;
    }

    @Override
    public String tableFieldsSql(String dataBaseName, String tableName) {
        return StrUtil.format("select\n" +
                "  name,\n" +
                "  type,\n" +
                "  comment,\n" +
                "  numeric_precision,\n" +
                "  numeric_scale,\n" +
                "  is_in_primary_key,\n" +
                "  CASE WHEN type LIKE 'Nullable%' THEN 'YES' ELSE 'NO' END AS is_nullable," +
                "  0 character_maximum_length\n" +
                "from\n" +
                "  system.columns\n" +
                "where\n" +
                "  database = '{}'\n" +
                "  and table = '{}'", dataBaseName, tableName);
    }

    @Override
    public String fieldName() {
        return "name";
    }

    @Override
    public String fieldType() {
        return "type";
    }

    @Override
    public String fieldComment() {
        return "comment";
    }

    @Override
    public String fieldKey() {
        return "is_in_primary_key";
    }

    @Override
    public String dataPrecision() {
        return "numeric_precision";
    }

    @Override
    public String dataScale() {
        return "numeric_scale";
    }

    @Override
    public String isNullable() {
        return "is_nullable";
    }

    @Override
    public String characterMaximumLength() {
        return "character_maximum_length";
    }
}
